<template>
  <el-drawer title="新增人员" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="工号" prop="jobNumber">
        <el-input v-model="formData.jobNumber" placeholder="请输入工号" />
      </el-form-item>
      <el-form-item label="姓名" prop="staffName">
        <el-input v-model="formData.staffName" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="所属部门" prop="configOrgDeptArchivesId">
        <el-select 
          v-model="deptName"
          filterable
          remote 
          value-key="id"
          placeholder="请选择所属部门"
          :remote-method="remoteDeptMethod"
          :loading="deptLoading"
          @change="changeDept"
        >
          <el-option
            v-for="item in deptNameList"
            :key="item['id']"
            :label="item['name']"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="紧急联系人1" prop="emergencyContact">
        <el-input v-model="formData.emergencyContact" placeholder="请输入紧急联系人" />
      </el-form-item>
      <el-form-item label="紧急联系人2" prop="spareEmergencyContact">
        <el-input v-model="formData.spareEmergencyContact" placeholder="请输入紧急联系人" />
      </el-form-item>
      <el-form-item label="所属班组" prop="teamId">
        <el-select 
          v-model="teamName" 
          filterable
          remote
          value-key="id"
          placeholder="请选择所属班组"
          :remote-method="remoteTeamMethod"
          :loading="teamLoading"
          @change="changeTeam"
        >
          <el-option
            v-for="(item) in teamNameList"
            :key="item['id']"
            :label="item['teamName']"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="岗位" prop="dictPost">
        <el-select v-model="formData.dictPost" placeholder="请选择岗位">
          <el-option
            v-for="dict, index in getIntDictOptions('config_post')"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="人员类别" prop="dictStaffType">
        <el-select v-model="formData.dictStaffType" placeholder="请选择人员类别">
          <el-option
            v-for="dict, index in getIntDictOptions('config_staff_type')"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="试用工资" prop="tryOutWage">
        <el-input v-model="formData.tryOutWage" placeholder="请输入试用工资" />
      </el-form-item>
      <el-form-item label="结算方式" prop="dictSettleAccountWay">
        <el-select v-model="formData.dictSettleAccountWay" placeholder="请选择在结算方式">
          <el-option
            v-for="dict, index in getIntDictOptions('config_settle_account_way')"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="入职时间" prop="entryTime">
        <el-date-picker
          v-model="formData.entryTime"
          type="date"
          value-format="x"
          placeholder="选择入职时间"
        />
      </el-form-item>
      <el-form-item label="离职时间" prop="dimissionTime">
        <el-date-picker
          v-model="formData.dimissionTime"
          type="date"
          value-format="x"
          placeholder="选择离职时间"
        />
      </el-form-item>
      <el-form-item label="性别" prop="dictSex">
        <el-select v-model="formData.dictSex" placeholder="请选择性别">
          <el-option
            v-for="dict in getIntDictOptions('dict_sex')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="在职状态" prop="dictStaffStatus">
        <el-select v-model="formData.dictStaffStatus" placeholder="请选择在职状态">
          <el-option
            v-for="dict in getIntDictOptions('dict_staff_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { getIntDictOptions } from '@/utils/dict'
import * as OrgStaffArchivesApi from '@/api/config/orgPeopleArchives'
import * as ComponentApi from '@/api/componentApi/index'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  jobNumber: undefined,
  staffName: undefined,
  configOrgDeptArchivesId: undefined, //所属部门id
  configOrgDeptArchivesName: undefined, //所属部门
  mobile: undefined,  //手机
  emergencyContact: undefined,
  spareEmergencyContact:undefined,
  teamId: undefined,
  teamName: undefined,
  dictPost: undefined,  //岗位
  dictStaffType: undefined, //人员类别
  dictSettleAccountWay: undefined,  //结算方式
  tryOutWage: undefined,  //试用工资
  remark: undefined,
  entryTime: undefined,
  dimissionTime: undefined,
  dictSex: undefined, //性别
  dictStaffStatus: undefined  //在职状态
})
const formRules = reactive({
  jobNumber: [{ required: true, message: '工号不能为空', trigger: 'blur' }],
  staffName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  configOrgDeptArchivesId: [{ required: true, message: '所属部门不能为空', trigger: 'blur' }],
  dictPost: [{ required: true, message: '岗位不能为空', trigger: 'blur' }],
  dictStaffType: [{ required: true, message: '人员类别不能为空', trigger: 'blur' }],
  dictSettleAccountWay: [{ required: true, message: '结算方式不能为空', trigger: 'blur' }],
  dictSex: [{ required: true, message: '性别不能为空', trigger: 'change' }],
  dictStaffStatus: [{ required: true, message: '在职状态不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

interface OptionTeam {
  id: number
  teamName: string
}
interface OptionDept {
  id: number
  name: string
}
const teamName = ref<OptionTeam>()
const deptName = ref<OptionDept>()
const teamNameList = ref<OptionTeam[]>([])
const deptNameList = ref<OptionDept[]>([])
const teamLoading = ref(false)  //班组长加载
const deptLoading = ref(false)  //部门加载

// 获取班组
const remoteTeamMethod = async (query: string) => {
  if (query) {
    teamLoading.value = true
    try {
      let res = await ComponentApi.getTeamList(query)
      teamNameList.value = res
    } finally {
      teamLoading.value = false
    }
  } else {
    teamNameList.value = []
  }
}

// 获取部门
const remoteDeptMethod = async (query: string) => {
  if (query) {
    deptLoading.value = true
    try {
      let res = await ComponentApi.getDeptList(query)
      deptNameList.value = res
    } finally {
      deptLoading.value = false
    }
  } else {
    deptNameList.value = []
  }
}

// 班组改动
const changeTeam = (val) => {
  formData.value.teamId = val.id
  formData.value.teamName = val.teamName
}

// 部门改动
const changeDept = (val) => {
  formData.value.configOrgDeptArchivesId = val.id
  formData.value.configOrgDeptArchivesName = val.name
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const res = await OrgStaffArchivesApi.getOrgStaffArchives(id)
      formData.value = res
      // 班组下拉框
      teamNameList.value = [{
        id: res.teamId,
        teamName: res.teamName
      }]
      teamName.value = {
        id: res.teamId,
        teamName: res.teamName
      }
      // 部门下拉框
      deptNameList.value = [{
        id: res.configOrgDeptArchivesId,
        name: res.configOrgDeptArchivesName
      }]
      deptName.value = {
        id: res.configOrgDeptArchivesId,
        name: res.configOrgDeptArchivesName
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (formData.value.dictStaffStatus === 10 && formData.value.dimissionTime) {
    message.notifyError('在职时，离职时间不能填写')
    return
  }
  if (formData.value.dictStaffStatus === 20 && !formData.value.dimissionTime) {
    message.notifyError('离职时，须填写离职时间')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrgStaffArchivesApi.OrgStaffArchivesVO
    if (formType.value === 'create') {
      await OrgStaffArchivesApi.createOrgStaffArchives(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrgStaffArchivesApi.updateOrgStaffArchives(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    jobNumber: undefined,
    staffName: undefined,
    configOrgDeptArchivesId: undefined, //所属部门id
    configOrgDeptArchivesName: undefined, //所属部门
    mobile: undefined,  //手机
    emergencyContact: undefined,
    teamId: undefined,
    teamName: undefined,
    dictPost: undefined,  //岗位
    dictStaffType: undefined, //人员类别
    dictSettleAccountWay: undefined,  //结算方式
    tryOutWage: undefined,  //试用工资
    remark: undefined,
    entryTime: undefined,
    dimissionTime: undefined,
    dictSex: undefined, //性别
    dictStaffStatus: undefined  //在职状态
  }
  formRef.value?.resetFields()
  teamName.value = {
    id: undefined,
    teamName: undefined
  }
  deptName.value = {
    id: undefined,
    name: undefined
  }
}
</script>
